package com.own.demo.blockchain.bitcoin;

import com.alibaba.fastjson.JSON;
import com.own.demo.blockchain.blockchain1.StringUtil;
import com.google.gson.GsonBuilder;
import lombok.Data;

import java.util.List;
import java.util.UUID;

/**
 * @Author liwenfeng
 * @Description 区块结构
 * @Date 2023/07/17/13:58
 * @Version 1.0
 */
@Data
public class Block3 {
    // 区块索引号
    private int index;
    // 当前区块hash值，区块唯一标识
    private String hash;
    // 生成区块的时间戳
    private long timestamp;
    // 当前区块的交易集合
    private List<Transaction> transactions;
    // 工作量证明，计算正确的hash值次数；
    private int nonce;
    // 前一个区块的hash
    private String previousHash;

    public Block3() {
        super();
    }

    public Block3(int index, long timestamp, List<Transaction> transactions, int nonce, String previousHash,String hash) {
        super();
        this.index = index;
        this.hash = hash;
        this.timestamp = timestamp;
        this.transactions = transactions;
        this.nonce = nonce;
        this.previousHash = previousHash;
    }

    /**
     * @return void
     * @Author liwenfeng
     * @Description 挖矿
     * @Param [
     * blockchain:整个区块链
     * txs：需要记账的交易记录
     * address:矿工钱包地址
     * ]
     * @Date 2023/7/17 14:23
     */
    public static void minBlock(List<Block3> blockchain, List<Transaction> txs, String address) {
        // 加入系统的交易
        Transaction sysTx = new Transaction(UUID.randomUUID().toString(), "", address, 10);
        txs.add(sysTx);
        // 获取前块区块链里的最后一个区块
        Block3 latestBlock = blockchain.get(blockchain.size() - 1);
        // 随机数
        int nonce = 1;
        String hash = "";
        while (true) {
            // 开发，工作量证明
            hash = StringUtil.applySha256(latestBlock.getHash()
                    + JSON.toJSONString(txs) + nonce);
            if (hash.startsWith("0000")) {
                System.out.println("=====计算结果正确，计算次数为：" +
                        nonce + ",hash:"
                        + hash);
                break;
            }
            nonce++;
        }
        Block3 newBlock = new Block3(latestBlock.getIndex() + 1, System.currentTimeMillis(), txs, nonce, latestBlock.getHash(), hash);
        blockchain.add(newBlock);
        System.out.println("挖矿后的区块链：" + JSON.toJSONString(blockchain));
        String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
        System.out.println("挖矿后的区块链：" +blockchainJson);
    }
}

